package org.chw.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.chw.netty.handler.EchoServerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: EchoServer
 * @Description: 建立服务器
 * @Autor: Vincent.Chen
 * @Create: 2018/6/8 15:08
 * @Version: 1.0
 **/
public class EchoServer {
    private final int port; //监听端口

    private static final Logger LOGGER = LoggerFactory.getLogger(EchoServer.class);

    public EchoServer(int port) {
        this.port = port;
    }


    /**
     * @return void
     * @Author: Vincent.Chen
     * @Description: 启动服务器
     * @Date 2018/6/8 15:35
     * @Param []
     **/
    public void start() throws InterruptedException {
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();  //创建NioEventLoopGroup
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            serverBootstrap.group(nioEventLoopGroup)            //创建ServerBootstrap
                    .channel(NioServerSocketChannel.class)      //指定使用NIO的传输Channel
                    .localAddress(port)                         //设置监听端口
                    .childHandler(new ChannelInitializer<SocketChannel>() { //添加 EchoServerHandler 到 Channel 的 ChannelPipeline
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            socketChannel.pipeline().addLast(
                                    new EchoServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind().sync();    //绑定的服务器;sync 等待服务器关闭
            LOGGER.info("{} started and listen on {}", EchoServer.class.getName(), channelFuture.channel().localAddress());
            channelFuture.channel().close().sync(); //关闭 channel 和 块，直到它被关闭
        } catch (InterruptedException e) {
            LOGGER.error("ERROR:", e);
        } finally {
            //nioEventLoopGroup.shutdownGracefully().sync();  //关机的 EventLoopGroup，释放所有资源
        }
    }
}
